package com.jy.admin.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.base.services.oss.OSSService;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.jsoniter.output.JsonStream;
import com.jy.admin.annotations.AdminSignIgnore;
import com.jy.admin.auth.anno.VisitorAccessible;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.BogLogDao;
import com.jy.admin.db.dao.PendingLogDao;
import com.jy.admin.db.entity.BogLogEntity;
import com.jy.admin.db.entity.PendingLogEntity;
import com.jy.admin.enums.PendingResultTypeEnum;
import com.jy.admin.enums.PendingStatusEnum;
import com.robert.vesta.util.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.telegram.telegrambots.bots.TelegramWebhookBot;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.PhotoSize;
import org.telegram.telegrambots.meta.api.objects.Update;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2021/12/18
 * Time: 4:50 下午
 */
@RestController
public class WebHookController {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebHookController.class);

    @Autowired
    private PendingLogDao pendingLogDao;

    @AdminSignIgnore
    @VisitorAccessible
    @RequestMapping("/bot/aa")
    public void webHook1(@RequestBody Update update) {

        LOGGER.info("== init bot===,update:{}", JsonStream.serialize(update));
    }

    @AdminSignIgnore
    @VisitorAccessible
    @RequestMapping("/bot/{token}/{targetChatId}")
    public void webHook(@RequestBody Update update, @PathVariable String token, @PathVariable String targetChatId) {
        Message message = update.getMessage();
        LOGGER.info("== bots update info ==,update:{}", JsonStream.serialize(update));

        Message replyToMessage = message.getReplyToMessage();
        if (replyToMessage != null) {
            try {
                String text = message.getText();
                String telMsgId = replyToMessage.getMessageId() + "#" + message.getChatId();
                if (StringUtils.isNotEmpty(text)) {
                    PendingLogEntity pendingLogEntity = pendingLogDao.selectByTelMsgId(telMsgId);
                    if (pendingLogEntity == null) {
                        LOGGER.error("== 找不到 需要回复的ID ==");
                        return;
                    }
                    pendingLogEntity.setReplyDetail(text);
                    if ("1".equals(text.trim())) {
                        pendingLogEntity.setResultContent("updated!!");
                        pendingLogEntity.setResultType(PendingResultTypeEnum.updated.getType());
                        pendingLogEntity.setStatus(PendingStatusEnum.has_reply.getStatus());
                    } else if ("2".equals(text.trim())) {
                        pendingLogEntity.setResultContent("invalid data,not received!!");
                        pendingLogEntity.setResultType(PendingResultTypeEnum.fake_info.getType());
                        pendingLogEntity.setStatus(PendingStatusEnum.has_reply.getStatus());
                    } else if ("3".equals(text.trim())) {
                        pendingLogEntity.setResultContent("partner system error!! client fixing");
                        pendingLogEntity.setResultType(PendingResultTypeEnum.need_waiting.getType());
                        pendingLogEntity.setStatus(PendingStatusEnum.has_reply.getStatus());
                    } else {
                        pendingLogEntity.setResultContent(text);
                        pendingLogEntity.setResultType(PendingResultTypeEnum.other.getType());
                        pendingLogEntity.setStatus(PendingStatusEnum.need_manual_reply.getStatus());
                    }

                    pendingLogDao.updateByPrimaryKey(pendingLogEntity);
                }

                sendMessage(token, message.getChatId(), "received!");
            } catch (Exception e) {
                LOGGER.error("== 收取消息发生错误 ==", e);
                sendMessage(token, message.getChatId(), URLEncoder.encode("error! contact the admin!"));
            }
        }
    }

    public static void sendMessage(String token, Long chatId, String text) {
        String page = HttpUtil.getPage("https://api.telegram.org/bot" + token + "/sendMessage?chat_id=" + chatId + "&text=" + text);
        LOGGER.info("==sendMessage send success ==,res:{}", page);
    }

    public byte[] downLoadBinary(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为10秒
        conn.setConnectTimeout(10 * 1000);
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36");
        //得到header
        Map<String, List<String>> map = conn.getHeaderFields();
        String fileName = map.get("Content-Disposition").get(0);
        fileName = fileName.substring(fileName.indexOf("=") + 1);
        System.out.println(fileName);
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取数据数组
        byte[] getData = readInputStream(inputStream);
        System.out.println(url + " download success");
        return getData;
    }


    public byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

}
